<template>
  <div class="upload-header">
    <div class="left">
      <a-upload
          v-model:file-list="files"
          name="file"
          action="/"
          :showUploadList="false"
          :beforeUpload="handleFileChange"
      >
        <a-dropdown-button   type="primary">
          上传文件
          <template #overlay>
            <a-menu>
              <a-menu-item key="1">

                <a-upload
                    v-model:file-list="files"
                    name="file"
                    action="/"
                    :showUploadList="false"
                    :beforeUpload="handleFileChange"
                >
                  上传文件
                </a-upload>
              </a-menu-item>
              <a-menu-item key="2">

                <a-upload
                    v-model:file-list="files"
                    name="file"
                    action="/"
                    :directory="true"
                    :beforeUpload="handleFileChange"
                    :showUploadList="false"
                >
                  上传文件夹
                </a-upload>
              </a-menu-item>


            </a-menu>
          </template>
        </a-dropdown-button>
      </a-upload>

      <a-button v-if="showCreateDir" style="margin-left: 30px" @click="createDir">新建文件夹</a-button>
    </div>
    <div class="right">
      <a-space style="margin-right: 20px">
        <ReloadOutlined @click="reload" style="font-size: 16px;cursor: pointer" />
      </a-space>
      <a-space v-if="selectFileList.length>0">

        <a-button @click="download()">下载</a-button>
        <a-button @click="openShareFrom">分享</a-button>
        <a-popconfirm
            :title="`确定删除个文件吗?`"
            ok-text="确定"
            cancel-text="取消"
            @confirm="removeFile()"

        >
          <a-button>删除</a-button>
        </a-popconfirm>


        <a-button @click="openDirTree"> 移动到...</a-button>


      </a-space>
    </div>
    <directoryTreeSelect v-if="show" :show="show"
                         :currentPathId="form.pid as number"
                         :openCreateBut="true" @close="close()"
                         @confirm="move"></directoryTreeSelect>
    <share-from-modal v-model="showShareFromModal" :selectFileList="selectFileList"
    @confirm="shareSuccess"
    />
    <share-link-modal v-model="showShareLinkModal" :shareInfo="shareInfo"/>
  </div>
</template>
<script setup lang="ts">
import {computed, defineComponent, ref, watch} from 'vue'
import {ReloadOutlined} from "@ant-design/icons-vue";
import directoryTreeSelect from '@/components/directory-tree-select/index.vue'
import shareFromModal from '../share/shareFromModal.vue'
import shareLinkModal from '../share/shareLinkModal.vue'
import {deleteFile, downloadFile, initUploadTask, moveFile, uploadFile,} from "@/api/disk/disk.ts";
import {message} from "ant-design-vue";
import {downloadBlob, fileChunk} from "@/utils/fileUtils.ts";
import {UploadQueueItem} from "@/types/files.ts";
import {FilePrimary} from "@/types/global.ts";
import {useSystemStore} from '@/stroe'
defineComponent({
  directoryTreeSelect,
  shareFromModal,
  shareLinkModal
})
const props = defineProps({
  selectFileList:{
    type:Array,
    default:()=>{
      return [];
    }
  },
  pid:{
    type:Number,
    default:1
  },
  createDir:{
    type:Boolean,
    default: true
  }
})
const emits = defineEmits(['refresh','createDir']);
const selectFileList = computed(()=>props.selectFileList)
const pid = computed(()=>props.pid)
const showCreateDir = computed(()=>props.createDir)
const showShareFromModal = ref(false);
const showShareLinkModal = ref(false);
const shareInfo = ref({});
const generateForm = ():FilePrimary=>{
  return{
    name:'',
    url:'',
    isDir:1,
    type:'',
    pid:1,
    size:''
  }
}
const systemStore = useSystemStore();
const form = ref(generateForm())
const files = ref([])
const show = ref(false);
const reload = ()=>{
  emits("refresh")
}
const createUploadTask = async (file:File)=>{
  console.time("计算hash值")
  const filePartList:any = await fileChunk(file);
  const partList = filePartList.map(item=>{
    return {
      hash:item.hash,
      blob:item.blob,
      partNumber:item.index
    }
  })
  console.timeEnd("计算hash值")
  console.log(partList)

  /* const item:UploadQueueItem = {
     uploadId:new Date().getTime().toString(),
     status:0,
     partList:partList,
     index:1,
     key:file.name,
     fileName:file.name,
     fileSize:file.size
   }
   console.log("item",item)
   const list = computed(()=>systemStore.uploadQueue);
   const arr = [...list.value,...[item]]
   console.log("arr",arr)
   systemStore.setUploadQueue(arr);*/
  initUploadTask({
    fileName:file.name,
    pid:form.value.pid as number,
    fileSize:file.size
  })
      .then((res:any)=>{
        if(res.code===200){
          console.log(res)
          const item:UploadQueueItem = {
            uploadId:res.result.uploadId,
            status:res.result.status,
            partList:partList,
            index:1,
            key:res.result.key,
            fileName:res.result.fileName,
            fileSize:file.size
          }
          const list = systemStore.uploadQueue;
          list.push(item);
          systemStore.setUploadQueue(list);
        }
      })

}
const openDirTree = ()=>{
  show.value = true;
}
const move = (data:number)=>{
  const key = new Date().getTime();
  const ids = selectFileList.value.map((item:any)=>item.id)
  show.value = false;
  message.loading({ content: '移动中', key,duration:0 })
  // @ts-ignore
  moveFile({fileIds:ids,targetId:data}).then((res:any)=>{
    if(res&&res.code===200){
      message.success({ content: '移动成功!', key});
      reload();
    }

  }).catch(e=>{
    console.error(e)
    message.error({ content: '移动失败!', key});
  })
}
const handleFileChange = (file:File)=>{
  console.log(file)
  console.log(file.size,1020 * 1024 * 100)
  if(file.size>=(1020 * 1024 * 50)){
    createUploadTask(file);
    return false;
  }

  uploadFile(file,form.value.pid as number).then(()=>{
    message.success("上传成功");
    reload();
  })
  return false;
}
const createDir = ()=>{
  emits("createDir")
}
const close = ()=>{
  show.value = false;
}
const download = (id?:number)=>{
  console.log("id",id)
  const ids = id?[id]: selectFileList.value.map((item:any)=>item.id);
  const key = new Date().getTime();
  message.loading({ content: '下载中', key,duration:0 })
  downloadFile(ids).then((res:any)=>{
    console.log("e44")
    let contentDisposition = res.headers['content-disposition'];
    let fileName = '';

    if (contentDisposition) {
      let fileNameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
      let matches = fileNameRegex.exec(contentDisposition);

      if (matches != null && matches[1]) {
        fileName = matches[1].replace(/['"]/g, '');
      }
    }
    downloadBlob(res.data,fileName)
    message.success({ content: '下载成功!', key});
  })
}
const removeFile = (id?:number)=>{
  const key = new Date().getTime();
  const loading = message.loading({ content: '删除中', key,duration:0 })
  const ids = id?[id]:selectFileList.value.map((item:any)=>item.id)
// @ts-ignore
  deleteFile(ids.join(",")).then((res:any)=>{
    if(res&&res.code===200){
      message.success({ content: '删除成功!', key});
      reload();
    }

  }).catch(()=>{
    loading();
  })
}
const openShareFrom = ()=>{
  showShareFromModal.value = true
}
const shareSuccess = (data:any)=>{
  console.log(data);
  showShareFromModal.value = false;
  showShareLinkModal.value = true;
  shareInfo.value = data;
}
watch(()=>pid.value,(value)=>{
  form.value.pid = value;
})
defineExpose({download,openDirTree,removeFile})
</script>
<style scoped lang="scss">
.upload-header{
  margin-bottom: 30px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .left,.right{
    display: flex;
    align-items: center;
  }
}
</style>
